package com.tool.rabbitmq;

import com.tool.rabbitmq.binding.RabbitBinding;
import com.tool.rabbitmq.binding.RabbitBindingProperties;
import com.tool.rabbitmq.constants.RabbitConstant;
import com.tool.rabbitmq.enums.ExchangeType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.core.RabbitAdmin;
import org.springframework.boot.CommandLineRunner;
import org.springframework.util.StringUtils;

/**
 * @author : zhaoxuan
 * @date : 2021/9/14 22:15
 * @description : BindingCommandLineRunner
 */
public class RabbitBindingCommandLineRunner implements CommandLineRunner {

    private Logger log = LoggerFactory.getLogger(getClass());

    private static final String EMPTY = "";

    private RabbitAdmin rabbitAdmin;

    private RabbitBindingProperties properties;

    public RabbitBindingCommandLineRunner(RabbitAdmin rabbitAdmin, RabbitBindingProperties properties) {
        this.rabbitAdmin = rabbitAdmin;
        this.properties = properties;
    }

    @Override
    public void run(String... args) throws Exception {
        log.info("rabbitmq-tool: start -- create rabbitmq exchange queue binding");
        properties.getBindings().parallelStream().forEach(this::createExchangeQueueBinding);
        log.info("rabbitmq-tool: end -- create rabbitmq exchange queue binding");
    }

    private void createExchangeQueueBinding(RabbitBinding rabbitBinding) {
        Queue queue = QueueBuilder.durable(rabbitBinding.getQueue()).build();
        rabbitAdmin.declareQueue(queue);
        Exchange exchange;
        if (ExchangeType.DIRECT  == rabbitBinding.getExchangeType()) {
            exchange = ExchangeBuilder.directExchange(rabbitBinding.getExchange()).durable(true).build();
        }else if (ExchangeType.FANOUT  == rabbitBinding.getExchangeType()){
            exchange = ExchangeBuilder.fanoutExchange(rabbitBinding.getExchange()).durable(true).build();
            rabbitBinding.setRoutingKey(EMPTY);
        }else if (ExchangeType.TOPIC  == rabbitBinding.getExchangeType()){
            exchange = ExchangeBuilder.topicExchange(rabbitBinding.getExchange()).durable(true).build();
        }else if (ExchangeType.DELAY  == rabbitBinding.getExchangeType()){
            exchange = ExchangeBuilder.topicExchange(RabbitConstant.DELAY_EXCHANGE).durable(true).build();
        }else{
            exchange = ExchangeBuilder.headersExchange(rabbitBinding.getExchange()).durable(true).build();
            rabbitBinding.setRoutingKey(rabbitBinding.getQueue());
        }
        rabbitAdmin.declareExchange(exchange);
        if (!StringUtils.isEmpty(rabbitBinding.getExchange())) {
            rabbitAdmin.declareBinding(BindingBuilder.bind(queue).to(exchange).with(rabbitBinding.getRoutingKey()).noargs());
        }
    }
}
